<?php

namespace Theatre\Server;

class Show extends \Theatre\Controller {
	/**
	 * Get all seats for this show
	 */
	function getAllSeats() {
		$this->view('JSON');

		$requestValid = $this->APIRequestIsValid($this->params);

		if ($requestValid['status'] == 'error') {
			$this->set($requestValid);

			return;
		}

		if (empty($this->params['hall_id']) || !is_numeric($this->params['hall_id'])) {
			$this->set(array(
				'status' => 'error',
				'message'  => 'Fill in the hall ID'
			));

			return;
		}

		if (empty($this->params['show_id']) || !is_numeric($this->params['show_id'])) {
			$this->set(array(
				'status'  => 'error',
				'message' => 'Fill in the show ID'
			));

			return;
		}

		if (empty($this->params['representation_id']) || !is_numeric($this->params['representation_id'])) {
			$this->set(array(
				'status'  => 'error',
				'message' => 'Fill in the representation ID'
			));

			return;
		}

		$partner = $requestValid['partner'];

		$ts = time();
		if (!empty($this->params['date'])) {
			$a = strptime($this->params['date'], '%Y-%m-%d');
			$a['tm_mon'] += 1;
			$a['tm_year'] += 1900;
			date_default_timezone_set('UTC');
			$ts = mktime(0, 0, 0, $a['tm_mon'], $a['tm_mday'], $a['tm_year']);

			if (empty($ts) || $ts <= 0) {
				$ts = time();
			}
		}

		$results = $this->model('PostGreSQL')->dbRunResult(
			'getAllSeats($1, $2, $3, $4, $5, $6, $7)',
			$this->params['hall_id'],
			$partner->id,
			$this->params['user_id'],
			$this->params['show_id'],
			date('Y-m-d 00:00:00', $ts),
			date('Y-m-d 23:59:59', $ts),
			$this->params['representation_id']
		);

		$seats = array(
			'available_seats'          => 0,
			'booked_seats'             => array(),
			'unconfirmed_booked_seats' => array()
		);

		while ($result = $this->model('PostGreSQL')->dbFetchObject($results)) {
			$seats['available_seats'] = $result->hall_seats;

			if (!empty($result->booked_seat)) {
				if ($result->booking_completed && $result->booking_completed == 't') {
					$seats['booked_seats'][] = $result->booked_seat;
				}
				else {
					$seats['unconfirmed_booked_seats'][] = $result->booked_seat;
				}
			}
		}

		$this->set(array(
			'status' => 'success',
			'seats'  => $seats
		));
	}
}
